//
//  ChatController.m
//  Topic1
//
//  Created by 孙添凤 on 16/12/7.
//  Copyright © 2016年 孙添凤. All rights reserved.
//

#import "ChatController.h"
#import "ChatCell.h"
#import "NetRequest.h"
#import "TopicObjModel.h"
#import "UIColor+CL.h"
#import "MJRefresh.h"
#import "ViewController.h"
#import "EducationAdminClient_URL.h"
#import "TZImagePickerController.h"
#import "ZMView.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "GroupMemberController.h"

@interface ChatController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>{
    TZImagePickerController *imagePickerVc;
    UITextView *contentText;
}
@property(nonatomic,strong)UIButton *btn1;
@property(nonatomic,strong)UIButton *btn2;
@property(nonatomic,strong)NSMutableArray *mutArr;
@property(nonatomic,strong)NSMutableDictionary *paramDic;
@property(nonatomic,strong)NSMutableArray *listArr;
@property(nonatomic,assign)NSInteger a;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,strong)UIButton *sendBtn;
//@property(nonatomic,strong)D3RecordButton *btn;//音频按钮
@property (strong, nonatomic)D3RecordButton *sendVoice;
@property(nonatomic,strong)NSMutableArray *lastArr;
@property(nonatomic,assign)NSInteger list_num;
@property(nonatomic,assign)float voicesecond;
@property(nonatomic,strong)UIImageView *seleImg;
@property(nonatomic,strong)UIImagePickerController *imagePickerController;


@property(nonatomic,strong)NSMutableArray *imagePaths;
@end

@implementation ChatController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.cusTabView.hidden = YES;
}

static const CGFloat MJDuration = 0.5;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    _isRefresh = NO;
    _a = 0;
    _lastArr =[NSMutableArray array];
    _mutArr = [NSMutableArray array];
    self.tbView =[[UITableView alloc]init];
    _paramDic =[NSMutableDictionary dictionary];
    _listArr =[NSMutableArray array];
    
    UIButton *rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightNavBtn.frame = CGRectMake(0, 0, 25, 25);
    [rightNavBtn setBackgroundImage:[UIImage imageNamed:@"index_out"] forState:UIControlStateNormal];
    [rightNavBtn addTarget:self action:@selector(RightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    [self.view addSubview:self.tbView];
    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom).offset(-49);
    }];
    self.tbView.delegate = self;
    self.tbView.dataSource = self;
    self.tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadMessage:) name:@"reloade" object:nil];

   
    
    UIView *textView =[[UIView alloc]init];
    [self.view addSubview:textView];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom).offset(-46);
        make.height.equalTo(@(49));
    }];
    textView.backgroundColor =[UIColor colorWithHex:0xf4f4f4];
    
//    _voiceBtn =[[UIButton alloc]init];
//    [textView addSubview:_voiceBtn];
//    [_voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(textView.mas_left).offset(12);
//        make.centerY.equalTo(textView.mas_centerY);
//        make.height.equalTo(@(27));
//        make.width.equalTo(@(27));
//    }];
//    [_voiceBtn setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateNormal];
    
    
    
    contentText =[[UITextView alloc]init];
    [textView addSubview:contentText];
    [contentText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(textView.mas_left).offset(11.5);
        make.right.equalTo(self.view.mas_right).offset(-79);
        make.centerY.equalTo(textView.mas_centerY);
        make.height.equalTo(@(33));
    }];
    contentText.layer.borderWidth = 0.5;
    contentText.layer.cornerRadius = 4;
    contentText.layer.borderColor =[[UIColor colorWithHex:0xabadb1]CGColor];
    contentText.delegate = self;
    
    
    _btn1 =[[UIButton alloc]init];
    [self.view addSubview:_btn1];
    [_btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(15);
        make.width.equalTo(@(150));
        make.top.equalTo(contentText.mas_bottom).offset(15);
        make.height.equalTo(@(30));
    }];
    _btn1.backgroundColor =[UIColor colorWithHex:0xab82ff];
    [_btn1 setTitle:@"选择消息类型" forState:UIControlStateNormal];
    [_btn1 addTarget:self action:@selector(btn1Click:) forControlEvents:UIControlEventTouchUpInside];
    _btn1.layer.cornerRadius = 5;
    
    _btn2 =[[UIButton alloc]init];
    [self.view addSubview:_btn2];
    [_btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.width.equalTo(@(150));
        make.top.equalTo(contentText.mas_bottom).offset(15);
        make.height.equalTo(@(30));
    }];
    _btn2.backgroundColor =[UIColor colorWithHex:0xab82ff];
    [_btn2 setTitle:@"选择人员类型" forState:UIControlStateNormal];
    [_btn2 addTarget:self action:@selector(btn2Click:) forControlEvents:UIControlEventTouchUpInside];
    _btn2.layer.cornerRadius = 5;
    
    _sendBtn =[[UIButton alloc]init];
    [textView addSubview:_sendBtn];
    [_sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.width.equalTo(@(54));
        make.centerY.equalTo(contentText.mas_centerY);
        make.height.equalTo(@(33));
    }];
//    _sendBtn.backgroundColor =[UIColor colorWithHex:0xcdc9c9];//0xab82ff
//    [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [_sendBtn addTarget:self action:@selector(btnClick3:) forControlEvents:UIControlEventTouchUpInside];
    [_sendBtn setBackgroundImage:[UIImage imageNamed:@"Sending"] forState:UIControlStateNormal];
//    _sendBtn.layer.cornerRadius = 5;
//    _sendBtn.titleLabel.font =[UIFont systemFontOfSize:13];
    _sendBtn.userInteractionEnabled = NO;
    
    
    _sendVoice =[[D3RecordButton alloc]init];
    [textView addSubview:_sendVoice];
    [_sendVoice setTitle:@"按住 说话" forState:UIControlStateNormal];
    [_sendVoice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(textView.mas_left).offset(11.5);
        make.right.equalTo(self.view.mas_right).offset(-79);
        make.centerY.equalTo(textView.mas_centerY);
        make.height.equalTo(@(33));
    }];
    [_sendVoice initRecord:self maxtime:100];//设置录音为时间
    _sendVoice.titleLabel.font =[UIFont systemFontOfSize:16];
    
    _sendVoice.backgroundColor =[UIColor whiteColor];
    
    [_sendVoice setTitleColor:[UIColor colorWithHex:0x858585] forState:UIControlStateNormal];
    [_sendVoice setBackgroundImage:[UIImage imageNamed:@"upload_btn_normal"] forState:UIControlStateNormal];
    [_sendVoice setBackgroundImage:[UIImage imageNamed:@"upload_btn_press"] forState:UIControlStateHighlighted];
    _sendVoice.hidden = YES;
    
    _sendVoice.voiceTIme = ^(float voicetime){
        _voicesecond = voicetime;
    };
    
    UIView *bottomView = [[UIView alloc]init];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
        make.height.equalTo(@(46));
    }];
    bottomView.backgroundColor =[UIColor colorWithHex:0xf4f4f4];
    bottomView.userInteractionEnabled = YES;
    
    UIView *l1=[[UIView alloc]init];
    [bottomView addSubview:l1];
    [l1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(bottomView.mas_top);
        make.height.equalTo(@(0.5));
    }];
    l1.backgroundColor =[UIColor colorWithHex:0xc3c3c5];
    
    int a = KWIDTH/5;
    for(int i=0;i<5;i++){
        UIView *v =[[UIView alloc]initWithFrame:CGRectMake(i*a, 0, a, 46)];
        [bottomView addSubview:v];
        UIImageView *img =[[UIImageView alloc]init];
        [v addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(v.mas_centerX);
            make.centerY.equalTo(v.mas_centerY);
            make.width.equalTo(@(31));
            make.height.equalTo(@(25));
        }];
        img.image =[UIImage imageNamed:[NSString stringWithFormat:@"%d",101+i]];
        img.tag = 11000+i;
        
        UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bottomBtnTap:)];
        [img addGestureRecognizer:tap];
        img.userInteractionEnabled = YES;
    }
    
    
    self.tbView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
//    self.tbView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [self footerRefresh];
//    }];
    
    // flag = YES;
    
    [self dataRequest];
    [self createLeftNavBar];
    [self creatImage];
    
}

-(void)RightClick:(UIButton *)btn{
    GroupMemberController *gcv =[[GroupMemberController alloc]init];
    [self.navigationController pushViewController:gcv animated:YES];
    gcv.channalID = self.pageID;
    gcv.customName = self.customName;
}

-(void)creatImage{
  

}



-(void)endRecord:(NSData *)voiceData{
    
    NSError *error;
    play = [[AVAudioPlayer alloc]initWithData:voiceData error:&error];
    play.volume = 9.0f;//音量
    float duration = (float)play.duration;
   
    contentText.hidden = NO;
    _sendVoice.hidden = YES;
    
    TopicObjModel *model = [[TopicObjModel alloc]init];
    model.voiceData = voiceData;
    model.isVoice = YES;
    model.voiceTime = duration;
    model.MESSCONTENT =[NSString stringWithFormat:@"%ld.音频",model.voiceTime];
    model.ismySelf = YES;
    model.voiceTime = duration;
    [_listArr addObject:model];
    [self.tbView reloadData];
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_listArr.count - 1 inSection:0];
    
    if (_listArr.count != 0) {
        [self.tbView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];//滚到最后一行
    }


}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicObjModel*model = [_listArr objectAtIndex:indexPath.row];
    NSError *error;
    if(model.isVoice){
        play = [[AVAudioPlayer alloc]initWithData:model.voiceData error:&error];
        play.volume = 9.0f;//音量
        float duration = (float)play.duration;
        [play play];
    }
}

-(void)bottomBtnTap:(UITapGestureRecognizer *)tap{
    NSLog(@"%ld",tap.view.tag);
    if(tap.view.tag==11000){//语音
        contentText.hidden = YES;
        _sendVoice.hidden = NO;
    }else if (tap.view.tag==11001){//相册
//        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//        imagePickerController.delegate = self;
//       
//        imagePickerController.allowsEditing = YES;
//        
//        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//       
//        [self presentViewController:imagePickerController animated:YES completion:^{}];
        
        
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    }else if (tap.view.tag==11002){//相机
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
        _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        _imagePickerController.allowsEditing = YES;
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
         [self presentViewController:_imagePickerController animated:YES completion:nil];
    }
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    TopicObjModel *model = [[TopicObjModel alloc]init];
    model.photo = UIImagePNGRepresentation(photos[0]);
    model.isphoto = YES;
    model.ismySelf = YES;
    model.MESSCONTENT = @"图片";
    [_listArr addObject:model];
    [self.tbView reloadData];
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_listArr.count - 1 inSection:0];
    
    if (_listArr.count != 0) {
        [self.tbView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];//滚到最后一行
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
 
    [picker dismissViewControllerAnimated:YES completion:^{}];
   
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    /* 此处info 有六个值
     08
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     09
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     10
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     11
     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
     12
     * UIImagePickerControllerMediaURL;       // an NSURL
     13
     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
     14
     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
     15
     */
    // 保存图片至本地，方法见下文
   
    [self saveImage:image withName:@"currentImage.png"];
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
   
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    
//    isFullScreen = NO;
//    
//    [self.imageView setImage:savedImage];
//   
//    self.imageView.tag = 100;
    
}

- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName

{
   
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
   
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

    [self dismissViewControllerAnimated:YES completion:^{}];
    
}

-(void)reloadMessage:(NSNotification *)n{
    NSDictionary *nic = [n object];
    _pageID = [nic objectForKey:@"channelId"];
     _isPUSH = YES;
    [self dataRequest2];
    
}
// 6666666666
-(void)createLeftNavBar{
    UIButton *leftNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftNavBtn.frame = CGRectMake(0, 0, 11, 37/2);
    [leftNavBtn setBackgroundImage:[UIImage imageNamed:@"形状1-19-拷贝-4"] forState:UIControlStateNormal];
    [leftNavBtn addTarget:self action:@selector(LeftClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:leftNavBtn];
    self.navigationItem.leftBarButtonItem = item;
    
}

-(void)LeftClick:(UIButton *)btn{
    NSLog(@"hsdjhaksjh");
     [self.navigationController popViewControllerAnimated:YES];
    if(_isPUSH){
         [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - Refresh
-(void)footerRefresh{
    [self.tbView.footer beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
//        [self setStyle];
        
        // 刷新表格
        if(_listArr.count==_a){
//             _a += 20;
//
        }else{
           //_a += 20;
        }
        
        [self dataRequest2];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tbView.footer endRefreshing];
    });
    
}

#pragma mark - setRithgAndUITableViewEditStyle
-(void)setStyle{
        self.tbView.editing = NO;
//        [self.tbView reloadData];
}
#pragma mark - Refresh
-(void)loadNewData{
    
    
    [self.tbView.header beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
        [self setStyle];
        
        // 刷新表格
        _isRefresh = YES;
         _totleNum = _totleNum-20;
        [self dataRequest2];
//        if(_a==0){
//          _totleNum = _totleNum-_totleNum%20+1-20;
//        }else{
//            _totleNum = _totleNum-20+1;
//        }
       
        _a = _a+1;
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tbView.header endRefreshing];
    });
    
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        [UIView animateWithDuration:0.2 animations:^{
            if(![contentText.text isEqualToString:@""]){
                _sendBtn.userInteractionEnabled = YES;
//               [_sendBtn setBackgroundColor:[UIColor colorWithHex:0xab82ff]];//输入框有内容
            }else{
                _sendBtn.userInteractionEnabled = NO;
//               [_sendBtn setBackgroundColor:[UIColor colorWithHex:0xcdc9c9]];
            }
            
            self.view.frame = CGRectMake(0, 0, KWIDTH, KHEIGHT);
        }];
        
         NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_listArr.count - 1 inSection:0];
        
        if (_listArr.count != 0) {
            [self.tbView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];//滚到最后一行
        }
        return NO;
    }else{
        if([contentText.text isEqualToString:@""]){
            _sendBtn.userInteractionEnabled = NO;
//            [_sendBtn setBackgroundColor:[UIColor colorWithHex:0xcdc9c9]];
        }else{
            _sendBtn.userInteractionEnabled = YES;
//            [_sendBtn setBackgroundColor:[UIColor colorWithHex:0xab82ff]];//输入框有内容
        }
    }
    return YES;
}



-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    [UIView animateWithDuration:0.2 animations:^{
        self.view.frame = CGRectMake(0, -250, KWIDTH, KHEIGHT);
    }];
    
    return YES;
}

-(void)btn2Click:(UIButton *)btn{
    UIAlertController *alert =[UIAlertController alertControllerWithTitle:nil message:@"请选择" preferredStyle:UIAlertControllerStyleActionSheet];
    NSArray *arr =[_mutArr[3]objectForKey:@"dicList"];
    for(int i=0;i<arr.count;i++){
        NSDictionary *dic = arr[i];
        UIAlertAction *action =[UIAlertAction actionWithTitle:[dic objectForKey:@"DIC_NAME"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_btn2 setTitle:[dic objectForKey:@"DIC_NAME"] forState:UIControlStateNormal];
            [_paramDic setObject:[dic objectForKey:@"DIC_ID"] forKey:[_mutArr[3] objectForKey:@"montageName"]];
        }];
        [alert addAction:action];
    }
    UIAlertAction *action =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:NO completion:nil];

    
}


-(void)btn1Click:(UIButton *)btn{
    
    UIAlertController *alert =[UIAlertController alertControllerWithTitle:nil message:@"请选择" preferredStyle:UIAlertControllerStyleActionSheet];
    NSArray *arr =[_mutArr[0]objectForKey:@"dicList"];
    for(int i=0;i<arr.count;i++){
        NSDictionary *dic = arr[i];
        UIAlertAction *action =[UIAlertAction actionWithTitle:[dic objectForKey:@"DIC_NAME"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_btn1 setTitle:[dic objectForKey:@"DIC_NAME"] forState:UIControlStateNormal];
            [_paramDic setObject:[dic objectForKey:@"DIC_ID"] forKey:[_mutArr[0] objectForKey:@"montageName"]];
        }];
        [alert addAction:action];
    }
    UIAlertAction *action =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:NO completion:nil];
}

-(void)btnClick3:(UIButton *)btn{
    [self sendMessage];
}
//上传参数获取
-(void)dataRequest{
    
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setObject:@"17798" forKey:@"tableId"];
    [param setObject:@"7691" forKey:@"pageId"];
    [param setObject:@"17796" forKey:@"mainTableId"];
    [param setObject:@"7686" forKey:@"mainPageId"];
    [param setObject:[NSString stringWithFormat:@"%@",_pageID]forKey:@"mainId"];
    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,RELATIONADD_URL];
    [NetRequest requestUrl:requestUrl andParamas:param andReturnBlock:^(NSData *data, NSError *error) {
        if(data!=nil&&!error){
            NSDictionary *obj =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            _mutArr =[[obj objectForKey:@"pageSet"] objectForKey:@"fieldSet"];
            [self dataRequest2];
            
        }else{
            
        }
    }];

}
//消息列表
-(void)dataRequest2{
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setObject:@"17798" forKey:@"tableId"];
    [param setObject:@"7694" forKey:@"pageId"];
    [param setObject:@"17796" forKey:@"mainTableId"];
    [param setObject:@"7686" forKey:@"mainPageId"];
    
    [param setObject:_pageID forKey:@"mainId"];
    [param setObject:@"20" forKey:@"limit"];
    
    NSInteger total ;
    if(!_isPUSH){
       total= _totleNum;
    }else{
      total= _totleNum2;
    }
    NSInteger pageNum =total-total%20+1;
    NSString *str = [NSString stringWithFormat:@"%ld",pageNum];
    [param setObject:str forKey:@"start"];
    NSLog(@"!!!!!!!!!!!!!%li",(long)_a);
    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,GOTOSCHOOL];
    [NetRequest requestUrl:requestUrl andParamas:param andReturnBlock:^(NSData *data, NSError *error) {
        if(data!=nil&&!error){
            NSDictionary *obj =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray *arr = [obj objectForKey:@"rows"];
//            if(_isRefresh||_isPUSH){
            NSMutableArray *aaa = [NSMutableArray array];
            
//            if(_a!=0){
//                NSMutableArray *aaa =[NSMutableArray arrayWithArray:arr];
//                [aaa addObject:_listArr];
//                _listArr = aaa;
//            }
//                        [_listArr removeAllObjects];
//            }
//            _isRefresh = NO;
            for(NSDictionary *dic in arr){
                TopicObjModel *model =[[TopicObjModel alloc]init];

                model = [model initWithDictionary:dic error:nil];
                NSString *ss =[[NSUserDefaults standardUserDefaults]objectForKey:@"USERID"];
                int a = [ss intValue];
                int b = [model.SEND_ID intValue];
                if(a==b){
                    model.ismySelf = YES;
                }
                [aaa addObject:model];
//                [_listArr addObject:model];
            }
            if(!_isPUSH){
                if(_isRefresh&&_totleNum>0){
                 [aaa addObjectsFromArray:_listArr];
                    _isRefresh = NO;
                }
//
            }
            _isPUSH = NO;
            if(_totleNum>0){
             _listArr = aaa;
            }
            
        
            
//            [_mutArr addObjectsFromArray:_listArr];
            [self.tbView reloadData];
            
            if(_a==0||_isPUSH){
            
            NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_listArr.count - 1 inSection:0];
            
            if (_listArr.count != 0) {
                [self.tbView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];//滚到最后一行
            }
            }
            _isPUSH = NO;

            
        }else{
            
        }
    }];
    

}
//发送消息
-(void)sendMessage{
    
    NSString *str =[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"USERID"]];
    [_paramDic setObject:str forKey:@"userId"];
    [_paramDic setObject:contentText.text forKey:[_mutArr[1] objectForKey:@"montageName"]];
    [_paramDic setObject:@"17798" forKey:@"tableId"];
    [_paramDic setObject:@"7691" forKey:@"pageId"];
//    [_paramDic setObject:@"" forKey:[_mutArr[4] objectForKey:@"montageName"]];
//    [_paramDic setObject:@"" forKey:[_mutArr[2] objectForKey:@"montageName"]];
    [_paramDic setObject:@"appMsg" forKey:@"strFlag"];
    [_paramDic setObject:@"1697" forKey:@"t0_au_17798_7691_36737"];
    [_paramDic setObject:@"user" forKey:@"userType"];//学生是stu 教师 user
    [_paramDic setObject:@"4" forKey:@"sendType"];
//    [_paramDic setObject:@"1703" forKey:@"t0_au_17796_7687_36740"];//学生1702  老师 1703
    [_paramDic setObject:@"1703" forKey:@"t0_au_17798_7691_36740"];//学生1702  老师 1703
    [_paramDic setObject:_pageID forKey:@"t0_au_17798_7691_36729"];
    [_paramDic setObject:@"17798" forKey:@"t0_au_17798_7691_36739"];
    [_paramDic setObject:userNameDes() forKey:@"t0_au_17798_7691_36974"];
    [_paramDic setObject:userId() forKey:@"t0_au_17798_7691_36975"];
//   [_paramDic setObject: getSessionId() forKey:@"sessionId"];
    
    
    
    
    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,ADD_Commit_URL];
//    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,ADDTOPIC_URL];
    
    NSString *ss = @"t0_au_17798_7691_36739=17798&t0_au_17798_7691_36751=&t0_au_17798_7691_36752=&tableId=17798&userType=user&pageId=7691&t0_au_17796_7687_36740=1703&t0_au_17798_7691_36731=0e0sf0isfsfsf&source=1&userId=917&t0_au_17798_7691_36729=73&sendType=4&sessionId=D2060A4B1EDE0DCA1173EA1AE9D3A62C&strFlag=appMsg";
    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    
//  
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
//    
//    // 存放新添加的cookie
//    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
//    
//    // 获取
//    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    
//    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
//        [cookieDic setObject:cookie.value forKey:cookie.name];
//    }
//    
//    // cookie重复，先放到字典去重，再进行拼接
//    for (NSString *key in cookieDic) {
//        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
//        [cookieValue appendString:appendString];
//    }
//    // 将cookie存到请求头中
//    [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
//  
//    [manager POST:requestUrl parameters:_paramDic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        NSLog(@"responseObject---->%@",responseObject);
//        [contentText resignFirstResponder];
//                    _sendBtn.userInteractionEnabled = NO;
//                    [_sendBtn setBackgroundColor:[UIColor colorWithHex:0xcdc9c9]];
//                    contentText.text = @"";
//                    [UIView animateWithDuration:0.5 animations:^{
//                        self.view.frame = CGRectMake(0, 64, KWIDTH, KHEIGHT-64);
//                    }];
//                    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_listArr.count - 1 inSection:0];
//        
//                    if (_listArr.count != 0) {
//                        [self.tbView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];//滚到最后一行
//                    }
//        //            [self loadNewData];
//                    [self dataRequest2];
//        
//    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
//        
//    }];
    
    [NetRequest requestUrl:requestUrl andParamas:_paramDic andReturnBlock:^(NSData *data, NSError *error) {
        if(data!=nil&&!error){
           NSString *result  =[[ NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"发送成功");
            [contentText resignFirstResponder];
            _sendBtn.userInteractionEnabled = NO;
            [_sendBtn setBackgroundColor:[UIColor colorWithHex:0xcdc9c9]];
            contentText.text = @"";
            [UIView animateWithDuration:0.5 animations:^{
                self.view.frame = CGRectMake(0, 64, KWIDTH, KHEIGHT-64);
            }];
            NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_listArr.count - 1 inSection:0];
            
            if (_listArr.count != 0) {
                [self.tbView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];//滚到最后一行
            }
//            [self loadNewData];
            [self dataRequest2];
        }else{
            
        }
    }];
    
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"str";
    if(indexPath.row==7){
        
    }
    ChatCell *cell =[tableView dequeueReusableCellWithIdentifier:str];
    TopicObjModel *model =[[TopicObjModel alloc]init];
   
//    if([model.MESSCONTENT isEqualToString:@"信息系"]){
        NSLog(@"+++++++++%ld______",(long)indexPath.row);
//    }
    NSString *ss =[[NSUserDefaults standardUserDefaults]objectForKey:@"USERID"];
//    int a = [ss intValue];
//    int b = [model.AFM_8 intValue];
     model = [_listArr objectAtIndex:indexPath.row];
    if(cell==nil){
        cell =[[ChatCell alloc]initIdentifier:str];
//        if(!model.ismySelf){
//            cell.rightName.hidden = YES;
//            cell.rightLa.hidden = YES;
//            cell.image2.hidden = YES;
//            cell.img2.hidden = YES;
//            cell.rightArrow.hidden = YES;
//            
//            
//            cell.leftLa.hidden = NO;
//            cell.leftName.hidden = NO;
//            cell.image.hidden = NO;
//            cell.leftArrow.hidden = NO;
//            cell.img.hidden = NO;
//        }else{
//            cell.leftLa.hidden = YES;
//            cell.leftName.hidden = YES;
//            cell.leftArrow.hidden = YES;
//            cell.image.hidden = YES;
//            cell.rightName.hidden = NO;
//            cell.rightLa.hidden = NO;
//            cell.image2.hidden = NO;
//            cell.img.hidden = YES;
//            cell.img2.hidden = NO;
//            cell.rightArrow.hidden = NO;
//            //        [_time mas_updateConstraints:^(MASConstraintMaker *make) {
//            //            make.right.equalTo(_image2.mas_right);
//            //        }];
//        }

    }

    [cell setModel:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.time.text = [NSString stringWithFormat:@"___%ld___%@",indexPath.row,model.AFM_12];
//    cell.leftLa.text = model.MESSCONTENT;
//    cell.rightLa.text = model.MESSCONTENT;
    [cell setNnnnnn:model.MESSCONTENT];
    
    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TopicObjModel *model =[_listArr objectAtIndex:indexPath.row];
    UILabel *la =[[UILabel alloc]init];
    la.text = model.MESSCONTENT;
    la.numberOfLines = 0;
    float hh = [la sizeThatFits:CGSizeMake(200, CGFLOAT_MAX)].height;//动态计算高度
    
    if(model.isphoto){
        return 180;
    }else{
        if(hh<25){
            return hh+70;
        }else{
            return hh+60;
        }
    }
    
//    [cell.image mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.height.equalTo(@(hh));
//    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArr.count;
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
